package at.bartinger.gameoflive;

public class GameOfLiveUpdater {
	
	public GameOfLiveUpdater() {}

	
	public void update(GameOfLiveThread mCanvasThread, long sleep){
		synchronized(mCanvasThread.cells){
			boolean [][] newCells = new boolean[mCanvasThread.cells.length][mCanvasThread.cells[0].length];

			int neighbours = 0;
			for (int i = 0; i < mCanvasThread.cells.length; i++) {
				for (int j = 0; j < mCanvasThread.cells[0].length; j++) {
					neighbours = countNeighbors(mCanvasThread.cells,i,j);
					if(mCanvasThread.cells[i][j]){
						//Rule 1,2
						if(neighbours < 2 || neighbours > 3){
							newCells[i][j]=false;
						}
						//Rule 3
						if(neighbours == 2 || neighbours == 3){
							newCells[i][j] = true;
						}
					}else{
						if(neighbours == 3){
							//Rule 4
							newCells[i][j] = true;
						}
					}
				}

			}
			mCanvasThread.cells = newCells;
		}
		mCanvasThread.getRenderer().generation++;
		try {
			Thread.sleep(sleep);
		} catch (InterruptedException e) {
			//Pech wenna deppat is
		}
	}

	private int countNeighbors(boolean board[][], int y, int x) {
		// TODO: berechne den richtigen Rueckgabewert.
		if(y>=board.length)
			return 0;
		if(x>=board[y].length)
			return 0;
		if(y<=-3||x<=-3)
			return 0;

		int count=0;
		int y2=y+1;
		int x2=x+1;
		int y1=0;
		if(y==0){
			y1=y;
		}
		else{
			y1=y-1;
		}
		int x1=x-1;
		for(int i=y1;i<=y2;i++){
			for(int j=x1;j<=x2;j++){
				try{
					if(j>board[i].length)
						break;
					if(board[i][j]== true)
						count++;
				}
				catch(ArrayIndexOutOfBoundsException e){
					if(j<0)
						continue;
					else
						break;


				}	

			}
		}
		if(board[y][x]==true)
			count--;

		return count;

	}
}
